/*
 * @Description: 缓存数据
 * @Author: DHL
 * @Date: 2022-01-15 09:05:04
 * @LastEditors: DHL
 * @LastEditTime: 2024-02-02 14:19:00
 */

import { defineStore } from 'pinia'
import { store } from '@/store'
import { apiCacheRefresh, apiCacheSearchList } from '@/api/common/cache'
import { storageUtils } from '@/utils/storageUtils'
import { DataDicModel } from '@/api/common/model/cacheModel'
import { useTableSettingStore } from './tableSetting'

export interface ICacheDataState {
  /**
   * key  [typeCode+dataValue]
   * value  字典对象
   */
  dataDicObj: Nullable<Map<string, DataDicModel>>

  /**
   * key  [typeCode]
   * value  字典集合
   */
  dataDic: Nullable<Map<string, Array<DataDicModel>>>

  /**
   * key  [typeCode+dataName]
   * value  字典值
   */
  dataValue: Nullable<Map<string, string>>

  /**
   * key  [typeCode+dataValue]
   * value  字典值名称
   */
  dataName: Nullable<Map<string, string>>

  /**
   * 系统配置
   */
  sysConfig: Nullable<Map<string, string>>

  /**
   * 用户配置
   */
  userConfig: any
}

/**
 * 数据缓存KEY
 */
const CACHE_DATA_KEY = 'TW-CACHE-DATA'

const cacheDataStore = defineStore({
  id: 'cacheDataStore',
  state: (): ICacheDataState => ({
    dataDicObj: null,
    dataDic: null,
    dataValue: null,
    dataName: null,
    sysConfig: null,
    userConfig: null
  }),
  getters: {},
  actions: {
    /**
     * 构建缓存数据
     */
    buildCacheDataAction() {
      if (this.dataDic && this.dataDic.size > 0) {
        return
      }

      const cacheData: ICacheDataState = storageUtils.getLocalItem(CACHE_DATA_KEY)
      if (cacheData && cacheData.dataDic && Object.keys(cacheData.dataDic).length > 0) {
        this.setCacheData(cacheData)
        return
      }

      this.searchCacheDataAction()
    },

    /**
     * 查询缓存数据
     */
    searchCacheDataAction() {
      apiCacheSearchList().then((result) => {
        if (result?.success) {
          this.setCacheData(result.data)
        } else {
          console.error(result?.message)
        }
      })
    },

    /**
     * 刷新缓存数据
     */
    refreshCacheDataAction() {
      apiCacheRefresh().then((result) => {
        if (result?.success) {
          this.setCacheData(result.data)
        } else {
          console.error(result?.message)
        }
      })
    },

    setCacheData(cacheData: ICacheDataState) {
      const { dataDic, sysConfig, userConfig } = cacheData

      storageUtils.setLocalItem({
        key: CACHE_DATA_KEY,
        value: cacheData
      })

      if (dataDic) {
        let dataDicMap: Map<string, Array<DataDicModel>> = new Map()
        let dataDicObjMap: Map<string, DataDicModel> = new Map()

        let dataValueMap: Map<string, string> = new Map()
        let dataNameMap: Map<string, string> = new Map()

        for (const [key, val] of Object.entries(dataDic)) {
          const value = val as Array<DataDicModel>

          dataDicMap.set(key, value)

          value.forEach((item) => {
            dataDicObjMap.set(`${key}${item.dataValue}`, item)

            dataValueMap.set(`${key}${item.dataName}`, item.dataValue)

            dataNameMap.set(`${key}${item.dataValue}`, item.dataName)
          })
        }
        this.dataDic = dataDicMap
        this.dataDicObj = dataDicObjMap

        this.dataValue = dataValueMap
        this.dataName = dataNameMap
      }

      if (sysConfig) {
        let sysConfigMap: Map<string, string> = new Map()
        for (const [key, val] of Object.entries(sysConfig)) {
          sysConfigMap.set(key, val)
        }
        this.sysConfig = sysConfigMap
      }

      // 构建表格配置
      useTableSettingStore().buildTableSettingAction(userConfig)
    },

    /**
     * 清理缓存数据
     */
    clearCacheData() {
      storageUtils.removeLocalItem(CACHE_DATA_KEY)
      this.dataDic = null
      this.dataValue = null
      this.dataName = null
      this.sysConfig = null
      this.userConfig = null
    }
  }
})

export function useCacheDataStore() {
  return cacheDataStore(store)
}
